package cn.xz.gobang.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import cn.xz.gobang.R
import cn.xz.gobang.base.BaseActivity
import cn.xz.gobang.bean.CommonLib
import cn.xz.gobang.bean.EventBusMessage
import cn.xz.gobang.bean.RoomSingle
import cn.xz.gobang.databinding.ActivityGetFriendBinding
import cn.xz.gobang.databinding.ActivityMoreBinding
import cn.xz.gobang.service.ServerUtils
import cn.xz.gobang.util.ARouter
import cn.xz.gobang.util.AppHelper

class GetFriendActivity: BaseActivity<ActivityGetFriendBinding>(R.layout.activity_get_friend,true) {

    private var mCountDownTime: CountDownTimer? = null //定时器

    private var closeSer = true

    override fun initData() {
        //开服务
        ServerUtils.startServer()

        mDataBind.tvMsg.text = "邀请人请输入名称 ${AppHelper.getLocalIpAddress()} 进行邀请"
        open20()
        //初始化自己的数据
        val mRoomSingle = RoomSingle()
        mRoomSingle.num = 1
        mRoomSingle.white = CommonLib.UserIP
        CommonLib.mData = mRoomSingle
    }

    private fun open20(){
        //开启20秒倒计时
        mCountDownTime = object : CountDownTimer(21 * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                mDataBind.tvDown.text =  "${millisUntilFinished/1000}"
            }
            override fun onFinish() {
                //倒计时结束，没人销毁
                finish()
            }
        }.start()
    }

    private fun stop20(){
        if (mCountDownTime != null){
            mCountDownTime?.cancel()
            mCountDownTime = null
        }
    }

    override fun initEvent() {

    }


    override fun initEventBus(message: EventBusMessage) {
        super.initEventBus(message)
        when (message.messageTag) {
            CommonLib.GET_USER_DATA -> {
                //收到配对消息
                val mN: String = message.messageBody as String
                mDataBind.tvDown.post {
                    stop20()
                    mDataBind.tvDown.text = "准备"
                    mDataBind.tvMsg.text = "等待房主开始游戏"
                    CommonLib.mData.num++
                    CommonLib.mData.black = mN
                }
            }
            CommonLib.OPEN_PLAY->{
                closeSer = false
                ARouter.to(SingleActivity::class.java,false)
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stop20()
        if (closeSer){
            //关闭服务
            ServerUtils.stopServer()
        }
    }
}